const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');

function getMultiplier(level) {
    if (level >= 1 && level <= 40) return 150;
    if (level >= 41 && level <= 70) return 200;
    if (level >= 71 && level <= 160) return 300;
    return 150;
}

function parseDoc(doc) {
    const map = new Map();
    const lines = doc.split(/\r?\n/);
    for (const line of lines) {
        if (!/^\d+\s*,/.test(line)) continue;
        const parts = line.split(',').map(s => s.trim());
        if (parts.length < 3) continue;
        const level = parseInt(parts[0], 10);
        const tenHour = Number(parts[2]);
        if (!Number.isNaN(level) && !Number.isNaN(tenHour)) {
            const m = getMultiplier(level);
            const std = Math.floor(tenHour / (m * 10 * 1.1));
            map.set(level, std);
        }
    }
    return map;
}

async function main() {
    const projectRoot = path.resolve(__dirname, '..');
    const docPath = path.join(projectRoot, 'doc', '训练经验.md');
    const doc = fs.readFileSync(docPath, 'utf8');
    const docStd = parseDoc(doc); // 包含 0 值

    const db = {
        host: process.env.DB_HOST || '43.143.253.188',
        port: parseInt(process.env.DB_PORT || '3306', 10),
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs',
    };
    const baseline = parseInt(process.env.BASELINE_FIGHTS || '1000', 10);

    let conn;
    try {
        conn = await mysql.createConnection(db);
        const [rows] = await conn.execute('SELECT level, experience, standard_exp_per_fight FROM level_experience ORDER BY level');

        let filled = 0;
        for (const r of rows) {
            const lvl = Number(r.level);
            const current = r.standard_exp_per_fight == null ? null : Number(r.standard_exp_per_fight);
            if (current != null) continue; // 已有值

            let value;
            if (docStd.has(lvl)) {
                value = docStd.get(lvl); // 可能为 0
            } else {
                const exp = Number(r.experience) || 0;
                value = Math.max(0, Math.floor(exp / baseline));
            }

            await conn.execute('UPDATE level_experience SET standard_exp_per_fight = ?, updated_at = NOW() WHERE level = ?', [value, lvl]);
            filled += 1;
        }
        console.log(`已补齐 ${filled} 行 standard_exp_per_fight`);
    } catch (e) {
        console.error('补齐失败:', e && e.message ? e.message : e);
        process.exit(1);
    } finally {
        if (conn) await conn.end();
    }
}

main().catch(e => { console.error(e); process.exit(1); });
